package com.situ.mall.controller.front;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.situ.mall.pojo.entity.Cart;
import com.situ.mall.pojo.entity.User;
import com.situ.mall.pojo.vo.CartProductVO;
import com.situ.mall.service.ICartService;
import com.situ.mall.util.JSONResult;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.object.UpdatableSqlQuery;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

@Controller
@RequestMapping("/cart")
public class FrontCartController {
	@Autowired
	private ICartService cartService;

	@ResponseBody
	@RequestMapping("/insert.shtml")
	public JSONResult insert(Cart cart, HttpSession session) {
		User user = (User) session.getAttribute("user");
		if (user == null) {
			return JSONResult.error("");
		}
		
		cart.setUserId(user.getId());
		cart.setChecked(1);
		boolean isSuccess = cartService.insert(cart);
		return JSONResult.ok("插入购物车成功");
	}
	
	@RequestMapping("/getCartListPage.shtml")
	public String getCartListPage(HttpSession session, Model model) {
		User user = (User) session.getAttribute("user");
		List<CartProductVO> list = cartService.selectByUserId(user.getId());
		model.addAttribute("list", list);
		return "/front/cart_list";
	}
	
	@ResponseBody
	@RequestMapping("/updateQuantity.shtml")
	public JSONResult updateQuantity(Cart cart, HttpSession session) {
		User user = (User) session.getAttribute("user");
		cart.setUserId(user.getId());
		boolean isSuccess = cartService.updateQuantity(cart);
		return isSuccess ? JSONResult.ok("更新成功") : JSONResult.error("更新失败");
	}
	
	@ResponseBody
	@RequestMapping("/updateStatus.shtml")
	public JSONResult updateStatus(Integer cartId, Integer checked) {
		boolean isSuccess = cartService.updateStatus(cartId, checked);
		return isSuccess ? JSONResult.ok("更新成功") : JSONResult.error("更新失败");
	}
	
	@ResponseBody
	@RequestMapping("/deleteById")
	public JSONResult deleteById(Integer cartId) {
		boolean isSuccess = cartService.deleteById(cartId);
		return isSuccess ? JSONResult.ok("删除成功") : JSONResult.error("删除失败");
	}
}
